var $book_manage_table;
var $category_manage_table;
var $order_manage_table;
var $order_detail_table;
var $user_manage_table;
var $categories;
var MOCK = false;
var root_url = "/bookstoreOnline"
if (MOCK) {
    document.write('<script src="../js/mock.js" type="text/javascript" charset="utf-8"></script>');
    document.write('<script src="../testAPI/adminAPI.js" type="text/javascript" charset="utf-8"></script>');
}
window.onload = function () {
    init_book_manage_table();
    nav_changer_listener();
}

function init_book_manage_table() {
    $book_manage_table = $('#book-mannage-table').bootstrapTable({
        url: root_url+'/get/book/manage/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbar: '#book-manage-toolbar', //工具栏
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order //排位命令（desc，asc）
            };
        },

        columns: [{
            field: 'b_name',
            title: '书本名称',
        }, {
            field: 'author',
            title: '作者',
        }, {
            field: 'price',
            title: '价格',
        }, {
            field: 'c_name',
            title: '分类',
        }, {
            field: 'b_id',
            title: '可供操作',
            align: 'center',
            valign: 'middle',
            width: 400,
            formatter: function (value, row, index) {
                return book_manage_table_formatter(value, row, index, 'offer')
            },
        },]
    });
}

function refresh() {
    //TEST
    $book_manage_table.bootstrapTable('refresh');
}

function book_manage_table_formatter(value, row, index, op) {
    let result;
    if (op == 'offer') {
        result =
            `
				<button type="button" class="btn btn-success" data-toggle="modal" data-target="#book-detail-modal" onclick="book_manage_op('${index}','detail')">详细信息</button>
				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#book-manage-modify-modal" onclick="book_manage_op('${index}','modify-modal')" 
								data-toggle="modal" data-target="#update_user_info_modal">修改信息</button>
				
		`;
    }
    return result;
}

//<button type="button" class="btn btn-danger" onclick="book_manage_op(${row.b_id},'delete')">删除</button>
function book_manage_op(...value) {
    get_category();
    //添加图书操作
    if (value[1] === 'add') {
        var formData = new FormData();
        let b_name = $('#b-name-add').val();
        let author = $('#author-add').val();
        let price = $('#price-add').val();
        let b_description = $('#description-add').val();
        let c_id = $('#category-add').val();
        let service = "insert";

        formData.append("image", $("#image-add")[0].files[0]);
        $.ajaxSettings.async = true;
        $.ajax({
            url: root_url + '/op/book?service=' + service + '&b_name=' + b_name + '&author=' +
                author + '&price=' + price + '&b_description=' + b_description + '&c_id=' + c_id,
            // url:root_url+'/op/book',
            /*接口域名地址*/
            type: 'post',
            data: formData,
            contentType: false,
            processData: false,
            success: function (res) {
                res = JSON.parse(res);
                console.log(res)
                if (res.code == "1") {
                    alert(res.msg);
                    location.reload();
                }
            }
        });
    }
    //添加分类选择
    else if (value[1] === 'start-modal') {
        console.log($categories)
        category_add = document.getElementById("category-add");
        for (let i = 0; i < $categories.length; ++i) {
            category_add.innerHTML += `<option value="${$categories[i].c_id}">${$categories[i].c_name}</option>`;
        }
    }
    //删除图书
    else if (value[1] === 'delete') {
        // $.post("/delete/book", {
        //     b_id: value[0]
        // }, function (res, status) {
        //     res = JSON.parse(res);
        //     if (res.line == "1") {
        //         alert("删除成功");
        //         refresh();
        //     }
        // })
        alert("没有删除功能")
    }
    //书籍详细信息
    else if (value[1] === 'detail') {
        //通过index获取书本信息
        let row = $book_manage_table.bootstrapTable('getData')[value[0]];
        console.log(row);
        let book_detail_modal = document.getElementsByClassName("book-detail-modal-body")[0];
        book_detail_modal.innerHTML = `
        <div style="width: 100%;">
                    <div style="margin: 0 auto;text-align: center;">
                        <img style="max-width: 50%;max-height: 50%;" src="${root_url}/staticFilepath/img/book/${row.imageName}" alt="">
                    </div>
                    </div>
                <div class="mt-3">
                    <h3>书名：${row.b_name}</h3>
                </div>
                <div class="ml-2">
                <div>
                    <p>
                        <span class="">分类：</span>
                        <span class="badge badge-success">${row.c_name}</span>
                    </p>
                </div>
                <p>作者：${row.author}</p>
                <p>价格：${row.price}元</p>
                <p>描述：${row.description}</p>
                </div>
        `
    }
    //添加更新模态框
    else if (value[1] === 'modify-modal') {
        //通过index获取书本信息
        let row = $book_manage_table.bootstrapTable('getData')[value[0]];
        //获取模态框
        let book_manage_modify_modal = document.getElementsByClassName("book-manage-modify-modal-body")[0];
        // 生成Select模块
        let select_box;
        for (let i = 0; i < $categories.length; ++i) {
            if ($categories[i].c_id === row.category_id) {
                select_box += `<option selected value="${$categories[i].c_id}">${$categories[i].c_name}</option>`;
                continue;
            }
            select_box += `<option  value="${$categories[i].c_id}">${$categories[i].c_name}</option>`;
        }
        book_manage_modify_modal.innerHTML = `
        <form>
            <div class="form-group">
                <label for="b-name-modify">书本名</label>
                <input type="text" class="form-control" id="b-name-modify" value="${row.b_name}">
            </div>
            <div class="form-group">
                <label for="author-modify">书本作者</label>
                <input type="text" class="form-control" id="author-modify" value="${row.author}">
            </div>
            <div class="form-group">
                <label for="price-modify">书本价格</label>
                <input type="text" value="${row.price}" onkeyup="if(event.keyCode !=37 && event.keyCode != 39)value=value.replace(/\\D/g,'')" class="form-control" id="price-modify">
            </div>
            <form>
                <div class="form-group">
                    <label for="image-modify">上传书本图片</label>
                    <input type="file" accept="image/jpeg" class="form-control-file" id="image-modify">
                    <!-- TODO 显示上传的图片 -->
                    <img id="image-add-show" src="${root_url}/staticFilepath/img/book/${row.imageName}" style="width: 50%;height: 50%">
                </div>
            </form>
            <div class="form-group">
                <label for="description-modify">书本描述</label>
                <textarea class="form-control" id="description-modify" rows="3">${row.description}</textarea>
            </div>
            <!-- 选择分类 -->
            <div class="form-group">
                <label for="category-modify">选择所属分类</label>
                <select class="form-control" id="category-modify">
                    ${select_box}
                </select>
            </div>
        </form>
        `

        document.getElementsByClassName("book-manage-modify-footer")[0].innerHTML = `
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="book_manage_op('${row.b_id}','modify')">提交</button>
        `
    }
    //更新信息
    else if (value[1] === 'modify') {

    }
}


//获取分类
function get_category() {
    $.ajaxSettings.async = false;
    $.post(root_url + "/get/category/table", {}, function (res, status) {
        if (status = "success") {
            res = JSON.parse(res);
            $categories = res.rows;
        }
    });
}

//导航条监听
function nav_changer_listener() {
    breadcrumb_items = document.getElementsByClassName("breadcrumb-item");
    for (i = 0; i < breadcrumb_items.length; i++) {
        breadcrumb_items[i].onclick = function () {
            breadcrumb_items[0].innerHTML = `<a href="#">图书管理</a>`;
            breadcrumb_items[1].innerHTML = `<a href="#">分类管理</a>`;
            breadcrumb_items[2].innerHTML = `<a href="#">订单管理</a>`;
            breadcrumb_items[3].innerHTML = `<a href="#">用户管理</a>`;

            let book_manage_warp = document.getElementsByClassName("book-manage-warp");
            let category_manage_warp = document.getElementsByClassName("category-manage-warp");
            let order_manage_warp = document.getElementsByClassName("order-manage-warp");
            let user_manage_warp = document.getElementsByClassName("user-manage-warp");
            book_manage_warp[0].style.display = "none";
            category_manage_warp[0].style.display = "none";
            order_manage_warp[0].style.display = "none";
            user_manage_warp[0].style.display = "none";
            value = this.value;
            let op_name;
            if (value == "1") {
                op_name = "图书管理"
                this.innerHTML = op_name;
                book_manage_warp[0].style.display = "block";
            }

            if (value == "2") {
                op_name = "分类管理"
                this.innerHTML = op_name;
                category_manage_warp[0].style.display = "block";
                init_category_manage_table();
            }

            if (value == "3") {
                op_name = "订单管理"
                this.innerHTML = op_name;
                order_manage_warp[0].style.display = "block";
                init_order_manage_table();
            }

            if (value == "4") {
                op_name = "用户管理"
                this.innerHTML = op_name;
                user_manage_warp[0].style.display = "block";
                init_user_manage_table();
            }

        }
    }
}

function category_manage_op(...value) {
    console.log(value);
    //添加分类信息
    if (value[1] === "add") {
        service = "insert";
        c_name = $("#c-name-add").val()
        c_d = $("#c_description-add").val()
        $.post(root_url + "/op/category", {
            service: service,
            c_name: c_name,
            c_description: c_d
        }, function (res, status) {
            if (status === "success") {
                res = JSON.parse(res);
                if (res.code == "1") {
                    alert(res.msg);
                    $category_manage_table.bootstrapTable('refresh');
                    location.reload();
                }
            }
        })
    }
    if (value[1] === "refresh") {
        $category_manage_table.bootstrapTable('refresh');
    }
    if (value[1] === "delete") {
        $.post(root_url+"/delete/category", {
            c_id: value[0]
        }, function (res, status) {
            if (status === "success") {
                res = JSON.parse(res);
                if (res.code == "1") {
                    alert(res.msg)
                    $category_manage_table.bootstrapTable('refresh');
                } else {
                    alert(res.msg)
                }
            }
        })
    }
    if (value[1] === "modify-modal") {
        let row = $category_manage_table.bootstrapTable('getData')[value[0]];
        console.log(row);
        let category_manage_modify_table = document.getElementsByClassName("category-manage-modify-modal-body")[0]
        category_manage_modify_table.innerHTML = `
        <form>
            <div class="form-group">
                <label for="c-name-modify">分类名</label>
                <input type="text" class="form-control" id="c-name-modify" value="${row.c_name}">
            </div>
            <div class="form-group">
                <label for="c_description-modify">分类描述</label>
                <textarea class="form-control" id="c_description-modify" rows="3" >${row.c_description}</textarea>
            </div>
        </form>
        `
        document.getElementsByClassName("category-manage-modify-footer")[0].innerHTML = `
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="category_manage_op('${row.c_id}','modify')">提交</button>
        `
    }
    if (value[1] === "modify") {
        console.log(value[1]);
    }
}

function init_category_manage_table() {
    $category_manage_table = $('#category-mannage-table').bootstrapTable({
        url: root_url + '/get/category/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbar: '#category-manage-toolbar', //工具栏
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order //排位命令（desc，asc）
            };
        },

        columns: [{
            field: 'c_name',
            title: '分类名',
        }, {
            field: 'c_description',
            title: '描述信息',
        }, {
            field: 'c_id',
            title: '可供操作',
            align: 'center',
            valign: 'middle',
            width: 400,
            formatter: function (value, row, index) {
                return category_manage_table_formatter(value, row, index, 'offer')
            }
        },]
    });
}

function category_manage_table_formatter(value, row, index, op) {
    let result;
    if (op == "offer") {
        result =
            `
				<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#category-manage-modify-modal" onclick="category_manage_op('${index}','modify-modal')" 
								data-toggle="modal" data-target="">修改信息</button>
				<button type="button" class="btn btn-danger" onclick="category_manage_op('${row.c_id}','delete')">删除</button>
		`;
    }
    return result;
}

function init_order_manage_table() {
    $order_manage_table = $('#order-manage-table').bootstrapTable({
        url: root_url+'/get/order/info/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbar: '#order-manage-toolbar', //工具栏
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                role: "admin"
            };
        },

        columns: [{
            field: 'orderId',
            title: '订单号',
        }, {
            field: 'info_num',
            title: '条目数量',
        }, {
            field: 'info_price',
            title: '订单总价格',
        }, {
            field: 'status',
            title: '订单状态',
            formatter: function (value, row, index) {
                return order_manage_table_formatter(value, row, index, 'status')
            },
        }, {
            field: 'u_name',
            title: '订货人',
        }, {
            field: 'b_id',
            title: '可供操作',
            align: 'right',
            valign: 'middle',
            width: 400,
            formatter: function (value, row, index) {
                return order_manage_table_formatter(value, row, index, 'offer')
            },
        },]
    });
}

function order_manage_table_formatter(value, row, index, op) {
    let result;
    if (op == "offer") {
        if (row.status == "0") {
            result = "无可用操作";
        } else if (row.status == "1") {
            result =
                `
                <button type="button" class="btn btn-success" onclick="order_manage_op('${row.orderId}','confirm')">确认受理</button>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_manage_op('${row.orderId}','detail')">详细信息</button>
			`;
        } else if (row.status == "2" || row.status == "4") {
            result = `
			    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_manage_op('${row.orderId}','detail')">详细信息</button>
			`;
        } else if (row.status == "3") {
            result = `
                <button type="button" class="btn btn-success" onclick="order_manage_op('${row.orderId}','confirm')">确认受理</button>
                <button type="button" class="btn btn-danger" onclick="order_manage_op('${row.orderId}','reject')">确认撤销</button>
                <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_manage_op('${row.orderId}','detail')">详细信息</button>
            `
        }
    } else if (op = "status") {
        if (value == "0") {
            result = "未付款"
        } else if (value == "1") {
            result = "未发货"
        } else if (value == "2") {
            result = "已发货"
        } else if (value == "3") {
            result = "待处理"
        } else if (value == "4") {
            result = "已撤销"
        }
    }
    return result;
}

function order_manage_op(...value) {
    //刷新
    if (value[1] == "refresh") {
        console.log(value)
        $order_manage_table.bootstrapTable('refresh');
    }
    //受理
    else if (value[1] == "confirm") {
        $.post(root_url + "/op/order/status", {
            orderId: value[0],
            des_status: "2"
        }, function (res, status) {
            res = JSON.parse(res)
            if (res.line == "1") {
                alert("发货成功");
                $order_manage_table.bootstrapTable('refresh');
            } else {
                alert("操作失败");
            }
        })
    }
    //确认撤销
    else if (value[1] == "reject") {
        $.post(root_url + "/op/order/status", {
            orderId: value[0],
            des_status: "4"
        }, function (res, status) {
            res = JSON.parse(res)
            if (res.line == "1") {
                alert("撤销成功");
                $order_manage_table.bootstrapTable('refresh');
            } else {
                alert("操作失败");
            }
        })
    }
    //详细信息
    else if (value[1] == "detail") {
        if ($order_detail_table == null) {
            init_order_detail_table(value[0]);
        } else {
            $order_detail_table.bootstrapTable('destroy');
            init_order_detail_table(value[0]);
        }
    }
}

function init_order_detail_table(orderId) {
    $order_detail_table = $('#order-detail-table').bootstrapTable({
        url: root_url+'/get/order/item/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                orderId: orderId,
            };
        },

        columns: [{
            field: 'b_name',
            title: '书本名称',
        }, {
            field: 'b_num',
            title: '书本数量',
        }, {
            field: 'i_price',
            title: '总价',
        },]
    });
}

function init_user_manage_table() {
    $user_manage_table = $('#user-manage-table').bootstrapTable({
        url: root_url + '/get/user/manage/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbarAlign: 'left', //工具栏的位置
        toolbar: '#user-manage-toolbar', //工具栏
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
            };
        },
        columns: [{
            field: 'u_name',
            title: '用户名',
        }, {
            field: 'cellphone',
            title: '座机',
        }, {
            field: 'mobilephone',
            title: '手机号码',
        }, {
            field: 'address',
            title: '地址',
        }, {
            field: 'email',
            title: '邮箱',
        }]
    });
}

function user_manage_op(...value) {
    console.log(value)
    if (value[1] == "refresh") {
        $user_manage_table.bootstrapTable('refresh');
    } else if (value[1] == "add") {
        let u_name = $("#u-name-add").val();
        let pwd = $("#pwd-add").val();
        let con_pwd = $("#con-pwd-add").val();
        let email = $("#email-add").val();
        let cellphone = $("#cellphone-add").val();
        let mobilephone = $("#mobilephone-add").val();
        let address = $("#address-add").val();
        if (pwd !== con_pwd) {
            alert("确认密码与密码不相同!")
            return
        }
        $.post(root_url + "/register", {
            uname: u_name,		//用户名
            pwd: pwd,		//密码
            email: email,	//邮箱
            cellphone: cellphone,   		//座机号码
            mobilephone: mobilephone, 		//移动电话
            address: address,     		//地址
        }, function (res, status) {
            res = JSON.parse(res)
            if (res.code == "0") {
                alert(res.msg);
            } else {
                alert(res.msg);
            }
        })
    }
}

function quit() {
    //TODO 清除存留的session
    $.post(root_url + "/quit", {}, function () {
        window.location = ".." + root_url + "/";
    });
}

function show_img(input){
    //实时显示图片
    let url = window.URL.createObjectURL(input.files[0]);
    document.getElementById("image-add-show").src = url;
}